﻿#region License

// { social }
// Patterns for building social software in .NET
// (c) 2008 Dimebrain
// http://www.dimebrain.com

#endregion

using System;
using System.Collections.Generic;

namespace Dimebrain.TweetSharp.Core.Extensions
{
    public static class HigherOrderExtensions
    {
        #region Delegates

        public delegate K Accumulator<T, K>(T x, K y);

        public delegate K Converter<T, K>(T item);

        #endregion

        public static IEnumerable<T> Filter<T>(this IEnumerable<T> source, Predicate<T> predicate)
        {
            var result = new List<T>();
            if (source != null)
            {
                foreach (var item in source)
                {
                    if (predicate(item))
                    {
                        result.Add(item);
                    }
                }
            }

            return result;
        }

        public static IEnumerable<K> Map<T, K>(this IEnumerable<T> source, Converter<T, K> converter)
        {
            var result = new List<K>();
            if (source != null)
            {
                foreach (var item in source)
                {
                    result.Add(converter(item));
                }
            }

            return result;
        }

        public static K Reduce<T, K>(this IEnumerable<T> source, K startValue, Accumulator<T, K> accumulator)
        {
            var result = startValue;
            if (source != null)
            {
                foreach (var item in source)
                {
                    result = accumulator(item, result);
                }
            }

            return result;
        }
    }
}